<template>
  <div class="chapterDetails">
    <van-nav-bar
      :title="courseName"
      left-arrow
      @click-left="backCourseList()"
      class="detail-header"
      fixed
    >
      <template #right>
        <van-icon
          name="wap-nav"
          size="18"
          @click="toggleChapterList"
          class="nav-icon"
        />
      </template>
    </van-nav-bar>

    <!-- 章节下拉框 -->
    <div v-if="showChapterList" class="chapter-dropdown" @click.stop>
      <div class="dropdown-content">
        <div class="dropdown-header">
          <span>章节列表</span>
          <van-icon name="cross" @click="toggleChapterList" size="16" />
        </div>
        <div class="chapter-list">
          <div
            v-for="item in chapterList"
            :key="item.id"
            class="chapter-item"
            :class="{ active: currentChapterId === item.id }"
            @click="selectChapter(item)"
          >
            <span class="chapter-title">{{ item.label }}</span>
            <van-icon v-if="currentChapterId === item.id" name="success" />
          </div>
        </div>
      </div>
    </div>

    <!-- 遮罩层 -->
    <div v-if="showChapterList" class="dropdown-mask"></div>

    <!-- 中间内容区域 -->
    <div class="content-area">
      <!-- Markdown内容展示 -->
      <div class="markdown-section" v-if="markdownContent">
        <div class="markdown-content">
          <MdEditor
            class="mdEditor"
            v-model="markdownContent"
            :toolbars="[]"
            :footers="[]"
            :katex="katexConfig"
            :preview="true"
            :editing="false"
            :show-toolbar="false"
            :show-footer="false"
          />
        </div>

        <!-- <div class="markdown-content" v-else>
          <div class="markdown-placeholder">
            <p>暂无内容</p>
          </div>
        </div> -->
      </div>

      <!-- 视频区域 -->
      <div class="video-section" v-if="videoList.length > 0">
        <div class="section-header">
          <img src="@/assets/images/video-icon.png" alt="视频讲解" />
          <span>视频讲解</span>
        </div>
        <div class="video-container">
          <div
            class="video-placeholder"
            v-for="item in videoList"
            :key="item.id"
          >
            <video
              :src="item.url"
              :poster="item.picUrl"
              controls
              preload="metadata"
              playsinline
              webkit-playsinline
              x5-video-player-type="h5"
              x5-video-player-fullscreen="false"
            ></video>
          </div>
        </div>
        <!-- <div class="video-container" v-else>
          <div class="video-placeholder">
            <p>暂无视频</p>
          </div>
        </div> -->
      </div>

      <!-- 答题 -->
      <div class="question-section">
        <div class="section-header">
          <img src="@/assets/images/kaohe-icon.png" alt="答题" />
          <span>答题</span>
        </div>
        <div class="question-content">
          <van-cell title="进入考核" @click="goToExam()" />
        </div>
      </div>

      <!-- 资源区域 -->
      <div class="resources-section" v-if="resources.length > 0">
        <div class="section-header">
          <img src="@/assets/images/resource-icon.png" alt="资源" />
          <span>资源</span>
        </div>
        <van-cell class="resources-content">
          <van-cell
            class="resource-item"
            v-for="item in resources"
            :key="item.id"
            :title="item.name"
            center
            is-link
            @click="openDoc(item)"
          />
        </van-cell>
        <!-- <div class="resources-content" v-else>
          <div class="resource-placeholder">
            <p>暂无资源</p>
          </div>
        </div> -->
      </div>
    </div>

    <!-- 底部导航栏 -->
    <div class="bottom-navigation">
      <div
        class="nav-button prev-button"
        @click="goToPrevChapter"
        :class="{ disabled: !hasPrevChapter }"
      >
        <img src="@/assets/images/previous-icon.png" alt="上一章节" />
        <span>上一章节</span>
      </div>

      <div class="nav-center" @click="goToXuebanChat()">
        <img src="@/assets/images/xueban-icon.png" alt="学伴" />
      </div>

      <div
        class="nav-button next-button"
        @click="goToNextChapter"
        :class="{ disabled: !hasNextChapter }"
      >
        <img src="@/assets/images/next-icon.png" alt="下一章节" />
        <span>下一章节</span>
      </div>
    </div>
  </div>
</template>

<script>
import { renderAsync } from "docx-preview";
import * as XLSX from "xlsx";
import { init } from "pptx-preview";
import { showToast } from "vant";
// 解决控制台警告
import { config } from "md-editor-v3";
config({
  katexConfig(base) {
    return {
      ...base,
      strict: false,
      // 启用自动换行
      throwOnError: false,
      // 允许在运算符处换行
      breakOnMultilineOperator: true,
      // 允许在关系符处换行
      breakOnRelation: true,
      // 最大宽度，超过会自动换行
      maxWidth: "100%",
    };
  },
});

export default {
  data() {
    return {
      courseId: "",
      courseName: "",
      showChapterList: false,
      chapterList: [],
      chapterId: null,
      currentChapterId: null,
      loading: false,

      // Markdown内容
      markdownContent: "",
      resources: [], // 多媒体资源
      videoList: [], // 视频列表
    };
  },
  computed: {
    // 当前章节索引
    currentChapterIndex() {
      return this.chapterList.findIndex(
        (chapter) => chapter.id === this.currentChapterId
      );
    },
    // 是否有上一章节
    hasPrevChapter() {
      return this.currentChapterIndex > 0;
    },
    // 是否有下一章节
    hasNextChapter() {
      return this.currentChapterIndex < this.chapterList.length - 1;
    },
  },
  watch: {
    "$route.query.chapterId": {
      handler(newVal) {
        if (newVal && this.chapterList.length > 0) {
          const targetChapter = this.chapterList.find(
            (chapter) => chapter.id == newVal
          );
          if (targetChapter) {
            this.currentChapterId = Number(newVal);
            this.chapterId = Number(newVal);
            this.getResources();
          }
        }
      },
      immediate: false, // 不立即执行，等章节列表加载完成
    },
  },
  created() {
    if (!window.katex) window.katex = {};
    window.katex.strict = "ignore";

    this.courseId = JSON.parse(localStorage.getItem("courseId"));
    this.courseName = localStorage.getItem("courseName");
    this.getChapterList();
  },
  methods: {
    // 切换章节列表显示状态
    toggleChapterList() {
      if (this.chapterList && this.chapterList.length == 0) {
        showToast("暂无章节");
        return;
      }
      this.showChapterList = !this.showChapterList;
    },

    // 章节列表
    getChapterList() {
      this.$axios
        .get(`/tes/course/auto/make/all-show-chapter?courseId=${this.courseId}`)
        .then((res) => {
          this.chapterList = res.data;

          // 检查是否有传入的chapterId参数
          const routeChapterId = this.$route.query.chapterId;
          if (routeChapterId) {
            this.currentChapterId = Number(routeChapterId);
            this.chapterId = Number(routeChapterId);
          } else {
            // 没有传入chapterId，使用第一个章节
            this.currentChapterId = Number(this.chapterList[0].id);
            this.chapterId = Number(this.chapterList[0].id);
          }

          this.getResources();
        });
    },

    // 获取资源
    getResources() {
      const loading = this.$loading({
        lock: true,
        text: "加载中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.$axios
        .get(
          `/tes/course/auto/make/chapter-resource-h5?courseId=${this.courseId}&chapterId=${this.currentChapterId}`
        )
        .then((res) => {
          this.markdownContent = res.data.kbContent;
          this.resources = res.data.resources;
          this.videoList = res.data.video;
        })
        .finally(() => {
          loading.close();
        });
    },

    // 选择章节
    selectChapter(item) {
      this.currentChapterId = item.id;
      this.getResources();
      this.showChapterList = false;
      showToast(`已切换到${item.label}`);
    },

    // 上一章节
    goToPrevChapter() {
      if (!this.hasPrevChapter) return;

      const prevChapter = this.chapterList[this.currentChapterIndex - 1];
      this.currentChapterId = prevChapter.id;
      showToast(`已切换到${prevChapter.label}`);
      this.getResources();
    },

    // 下一章节
    goToNextChapter() {
      if (!this.hasNextChapter) return;

      const nextChapter = this.chapterList[this.currentChapterIndex + 1];
      this.currentChapterId = nextChapter.id;
      showToast(`已切换到${nextChapter.label}`);
      this.getResources();
    },

    // 进入学伴对话
    goToXuebanChat() {
      if (this.chapterList && this.chapterList.length == 0) {
        showToast("暂无章节，无法使用AI学伴");
        return;
      }
      this.$router.push({
        name: "XuebanChat",
        query: { chapterId: this.currentChapterId },
      });
    },

    // 进入答题
    goToExam() {
      if (this.chapterList && this.chapterList.length == 0) {
        showToast("暂无章节，无法进入考核");
        return;
      }
      this.$router.push({
        name: "StuExam",
        query: { chapterId: this.currentChapterId },
      });
    },

    async openDoc(item) {
      const fileType = item.fileType;
      const fileUrl = item.url;

      // 用户点击时立刻打开新窗口（不会被拦截）
      const newWin = window.open("", "_blank");
      newWin.document.write(
        `<html>
      <head><title>文件预览</title></head>
      <body><div id="preview-wrapper">加载中，请稍候...</div></body>
    </html>`
      );

      try {
        if (fileType === "docx") {
          const response = await fetch(fileUrl);
          const blob = await response.blob();

          // 清空占位文字
          newWin.document.body.innerHTML = "";
          // 添加样式
          const style = newWin.document.createElement("style");
          style.innerHTML = `*{margin:0;padding:0;}`;
          newWin.document.head.appendChild(style);

          await renderAsync(blob, newWin.document.body, null, {
            className: "docx",
            inWrapper: true,
          });
        } else if (fileType === "xlsx") {
          const response = await fetch(fileUrl);
          const arrayBuffer = await response.arrayBuffer();
          const workbook = XLSX.read(arrayBuffer, { type: "array" });
          const sheet = workbook.Sheets[workbook.SheetNames[0]];
          const html = XLSX.utils.sheet_to_html(sheet);

          newWin.document.body.innerHTML = html;
          const style = newWin.document.createElement("style");
          style.innerHTML = `
        table { border-collapse: collapse; width: 100%; font-family: Arial, sans-serif; }
        th, td { border: 1px solid #999; padding: 6px 10px; text-align: left; }
        th { background-color: #f0f0f0; font-weight: bold; }
      `;
          newWin.document.head.appendChild(style);
        } else if (fileType === "pptx") {
          const response = await fetch(fileUrl);
          const arrayBuffer = await response.arrayBuffer();

          newWin.document.body.innerHTML = `<div id="pptx-wrapper"></div>`;

          // 延迟确保 DOM 可用
          setTimeout(() => {
            const container = newWin.document.getElementById("pptx-wrapper");
            const viewer = init(container, { width: 1200, height: "100%" });
            viewer.preview(arrayBuffer);
          }, 50);
        } else {
          // 其他文件类型直接打开
          newWin.location.href = fileUrl;
        }
      } catch (error) {
        console.error("文件预览失败:", error);
        newWin.document.body.innerHTML = `<p style="color:red;">文件预览失败，请重试或检查文件是否可访问</p>`;
      }
    },

    // 返回课程列表
    backCourseList() {
      this.$router.push("/courseInfo");
    },
  },
};
</script>

<style lang="scss" scoped>
.chapterDetails {
  background-color: #e7effc;

  .detail-header {
    background: #fff;
    --van-nav-bar-title-text-color: #1f2937;
    --van-nav-bar-icon-color: #6b7280;

    .nav-icon {
      cursor: pointer;
      transition: transform 0.2s ease;

      &:hover {
        transform: scale(1.1);
      }
    }
  }

  // 章节下拉框
  .chapter-dropdown {
    position: fixed;
    top: 46px; // nav-bar的高度
    right: 16px;
    z-index: 1000;
    min-width: 280px;
    max-width: 320px;

    .dropdown-content {
      background: #fff;
      border-radius: 12px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
      overflow: hidden;
      animation: slideDown 0.3s ease-out;

      .dropdown-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 16px 20px;
        background: #f8fafc;
        border-bottom: 1px solid #e2e8f0;

        span {
          font-size: 16px;
          font-weight: 600;
          color: #1f2937;
        }

        .van-icon {
          color: #6b7280;
          cursor: pointer;
          transition: color 0.2s ease;

          &:hover {
            color: #374151;
          }
        }
      }

      .chapter-list {
        max-height: 300px;
        overflow-y: auto;

        .chapter-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 12px 20px;
          cursor: pointer;
          transition: all 0.2s ease;
          border-bottom: 1px solid #f1f5f9;

          &:hover {
            background: #f8fafc;
          }

          &.active {
            background: #eff6ff;
            border-left: 3px solid #3b82f6;

            .chapter-title {
              color: #3b82f6;
              font-weight: 600;
            }

            .van-icon {
              color: #3b82f6;
            }
          }

          &:last-child {
            border-bottom: none;
          }

          .chapter-title {
            font-size: 14px;
            color: #374151;
            flex: 1;
            margin-right: 8px;
          }

          .van-icon {
            color: #10b981;
            font-size: 16px;
          }
        }
      }
    }
  }

  // 遮罩层
  .dropdown-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 999;
    background: rgba(0, 0, 0, 0.1);
    animation: fadeIn 0.2s ease-out;
  }

  // 内容区域
  .content-area {
    padding: 20px;
    padding-bottom: 80px; // 为底部导航栏留出空间

    // 通用区域样式
    .markdown-section,
    .video-section,
    .quiz-section,
    .resources-section,
    .question-section {
      background: #fff;
      border-radius: 12px;
      margin-bottom: 20px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
      overflow: hidden;
    }
    .markdown-section {
      margin-top: 40px;
    }

    // 区域标题
    .section-header {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 10px 16px;
      // background: #f8fafc;
      // border-bottom: 1px solid #e5e7eb;
      font-size: 15px;
      color: #9094ac;
      img {
        width: 25px;
        height: 25px;
      }

      .van-icon {
        color: #3b82f6;
      }
    }

    // Markdown内容区域
    .markdown-content {
      width: 100%;
      height: 100%;
      .markdown-placeholder {
        width: 100%;
        height: 200px;
        display: flex;
        align-items: center;
        justify-content: center;
        p {
          color: #64748b;
          font-size: 14px;
        }
      }
      // 预览
      .mdEditor {
        border: none;
        width: 100%;
        :deep(.md-editor-input-wrapper) {
          width: 0 !important;
        }
        :deep(.md-editor-resize-operate) {
          width: 0;
        }
        :deep(.md-editor-preview-wrapper::-webkit-scrollbar) {
          display: none;
        }
        :deep(.md-editor-katex-inline) {
          max-width: 100%;
          display: inline-block;
          white-space: normal !important;
        }

        /* 关键：重置 Katex 的样式 */
        :deep(.katex) {
          max-width: 100% !important;
          display: inline-block !important;
          white-space: normal !important;
          overflow-wrap: break-word !important;
        }

        /* Katex 内部元素允许换行 */
        :deep(.katex-html) {
          white-space: normal !important;
          max-width: 100% !important;
        }

        /* 公式基础包装器 */
        :deep(.katex .base) {
          white-space: normal !important;
          display: inline !important;
        }

        /* 数学符号元素 */
        :deep(.katex .mord),
        :deep(.katex .mbin),
        :deep(.katex .mrel),
        :deep(.katex .mopen),
        :deep(.katex .mclose) {
          display: inline !important;
          white-space: normal !important;
        }
      }
    }

    // 视频区域
    .video-container {
      padding: 20px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      gap: 20px;
      .video-placeholder {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 200px;
        border-radius: 8px;
        video {
          width: 100%;
          height: 100%;
          border-radius: 8px;
          background-color: #000;
          object-fit: contain;
        }
        p {
          margin: 8px 0;
          color: #64748b;
          font-size: 14px;
        }

        .video-duration {
          font-size: 12px;
          color: #94a3b8;
        }
      }
    }

    // 资源区域
    .resources-content {
      .resource-item {
        padding: 10px 0;
        // background: #f8fafc;
        // border: 1px solid #e5e7eb;
        transition: all 0.2s ease;
        text-align: left;
        :deep(.van-cell__title) {
          max-width: 100%;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
      .resource-placeholder {
        width: 100%;
        height: 200px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        p {
          color: #64748b;
          font-size: 14px;
        }
      }
    }

    // 答题
    .question-content {
      .question-item {
        display: flex;
        align-items: center;
        padding: 16px;
        background: #f8fafc;
        border-radius: 8px;
        margin-bottom: 12px;
        border: 1px solid #e5e7eb;
        transition: all 0.2s ease;
      }
    }
  }

  // 底部导航栏
  .bottom-navigation {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 70px;
    background: #fff;
    border-top: 1px solid #e5e7eb;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 30px;
    z-index: 1000;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);

    .nav-button {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      gap: 4px;
      color: #374151;
      font-size: 14px;
      cursor: pointer;

      img {
        width: 20px;
        height: 24px;
      }

      &:hover:not(.disabled) {
        background: #e5e7eb;
        transform: translateY(-1px);
      }

      &.disabled {
        opacity: 0.4;
        cursor: not-allowed;
        background: #f9fafb;
        color: #9ca3af;
      }
    }

    .nav-center {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 60px;
      height: 40px;
      background: #f8fafc;
      border-radius: 50%;
      color: #6b7280;
      transition: all 0.2s ease;
    }
  }
}

// 动画
@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

// 滚动条样式
.chapter-list::-webkit-scrollbar {
  width: 4px;
}

.chapter-list::-webkit-scrollbar-track {
  background: #f1f5f9;
}

.chapter-list::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 2px;
}

.chapter-list::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}
</style>
